import { createFileRoute, Outlet } from '@tanstack/react-router'
import { userQueryOptions } from '@/lib/api'
import { Button } from '@/components/ui/button'


const Login = () => {
    return (
        <div>
            <p className='mb-5'>You have to login or register</p>
            <Button className='mr-5'><a href="/api/login">Login</a></Button>
            <Button><a href="/api/register">Register</a></Button>
        </div>
    )
}

const Component = () => {
    const { user } = Route.useRouteContext()
    if (!user) {
        return <Login />
    }
    return <Outlet />
}

export const Route = createFileRoute('/_authenticated')({
    beforeLoad: async ({ context }) => {
        try {
            const data = await context.queryClient.fetchQuery(userQueryOptions)
            return data
        } catch {
            return { user: null }
        }
    },
    component: Component
})